package com.wlstock.funi.ui;

import java.util.List;

import com.android.volley.VolleyError;
import com.wlstock.funi.app.FundApplication;
import com.wlstock.funi.model.OperateModel;
import com.wlstock.funi.request.EventBusConstants;
import com.wlstock.funi.request.NetWorkListener;
import com.wlstock.funi.request.SinaPriceRequest;
import com.wlstock.funi.runnable.ZXRealPrice;
import com.wlstock.funi.runnable.ZXRealPrice.PriceListener;
import com.wlstock.funi.utils.StockUtils;

public class ThunderPriceReq implements NetWorkListener, PriceListener {

	private int tradeType;
	private String stkCode;
	public ThunderPriceListener tListener;
	
	public void request(String stkCode, int tradeType){
		if (!FundApplication.isLogSuccess) {
			//用新浪获取最新价格
			SinaPriceRequest sinaReq = new SinaPriceRequest();
			sinaReq.listener = this;
			sinaReq.request(stkCode, EventBusConstants.EVENT_STOCKS_UPDATE_ONE_PRICE);
		}else {
			//用证券公司的最新价格
			ZXRealPrice curPrice = null;
			if (tradeType == OperateModel.TradeType_BUY) {
				curPrice = new ZXRealPrice(ZXRealPrice.BSFLAG_BUY, stkCode);
			}else if (tradeType == OperateModel.TradeType_SELL){
				curPrice = new ZXRealPrice(ZXRealPrice.BSFLAG_SAILE, stkCode);
			}
			if (curPrice!=null) {
				curPrice.pListener = this;
				curPrice.request();	
			}
			
		}
	}

	@Override
	public void onErrorResponse(VolleyError error, EventBusConstants eventCode) {
		if (eventCode == EventBusConstants.EVENT_STOCKS_UPDATE_ONE_PRICE) {
			deliverPrice("0");
		}
	}

	@Override
	public void onErrorResponse(VolleyError error, String eventCode) {
		
	}

	@Override
	public void onResponse(String response, EventBusConstants eventCode) {	
		if (eventCode == EventBusConstants.EVENT_STOCKS_UPDATE_ONE_PRICE) {
			//x待测试
			float curPrice = StockUtils.parseSinaOnePrice(response, stkCode);
			deliverPrice(String.valueOf(curPrice));
		}
	}

	private void deliverPrice(String price) {
		if (tListener!=null) {
			tListener.getPrice(price);
		}
	}

	@Override
	public void onResponse(String response, String eventCode) {

		
	}
	
	public interface ThunderPriceListener{
		public void getPrice(String price);
	}

	@Override
	public void onUpdatePriceSuccess(List<String> priList) {
		if (priList == null) {
			deliverPrice("0");
		}else {
			if (tradeType == OperateModel.TradeType_BUY) {
				//返回买1价格
				deliverPrice(priList.get(5));
			}else if (tradeType == OperateModel.TradeType_SELL) {
				//返回卖1价格
				deliverPrice(priList.get(4));	
			}
		}
	}
	
}
